package cn.topcodes.tcsf.admin.jms;

import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcode.unicorn.utils.SpringContextHolder;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.utils.dist.DistEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class DistMessageReceiver implements MessageListener {

	private Logger logger = LoggerFactory.getLogger(DistMessageReceiver.class);

	@Autowired
	private DistEventRegister distEventRegister;

	@Override
	public void onMessage(Message msg) {
		try {
			TextMessage textMsg = (TextMessage) msg;
			if(StringUtil.isBlank(textMsg.getText())) {
				return;
			}
			DistEvent distEvent = JsonUtil.parse(textMsg.getText(), DistEvent.class);
			if(distEvent == null) {
				return;
			}
			Class clazz = distEventRegister.get(distEvent.getType());
			if(clazz == null) {
				return;
			}
			Object obj = distEvent.unpack(clazz);
			SpringContextHolder.publishEvent(obj);
		} catch (JMSException e) {
			logger.error("JMS消息接收处理发送错误", e);
		}
	}

}


